import { Component, Input, OnDestroy, OnInit } from '@angular/core';

@Component({
  selector: 'app-count-down',
  templateUrl: './count-down.component.html',
  styleUrls: ['./count-down.component.less'],
})
export class CountDownComponent implements OnInit, OnDestroy {
  @Input() startTime: Date = new Date();
  @Input() endTime!: Date;
  countDown!: string;
  timer: any;
  constructor() {}

  ngOnInit() {
    this.startCountDown();
  }
  ngOnDestroy(): void {
    clearInterval(this.timer);
  }
  diffDateInSec(start: Date, end: Date, interval: number): string {
    let diff = Math.floor(end.getTime() - start.getTime()) / 1000;
    diff -= interval;
    let { day, hour, minute, second } = {
      day: Math.floor(diff / 3600 / 24),
      hour: Math.floor((diff / 3600) % 24),
      minute: Math.floor((diff / 3600) % 60),
      second: Math.floor(diff % 60),
    };
    return `${hour}:${minute}:${second}`;
  }
  startCountDown() {
    let i = 0;
    this.timer = setInterval(() => {
      i++;
      this.countDown = this.diffDateInSec(this.startTime, this.endTime, i);
    }, 1000);
  }
}
